package com.wemew.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.wemew.common.enums.error.Error;
import com.wemew.common.exceptionhandler.GuliException;
import lombok.Data;

import static com.wemew.common.enums.error.Error.Error2001;

//统一返回结果的类
@Data
public class R {

    /**
     * 服务端的响应状态
     */
    private int status;
    /**
     * 服务端的响应状态
     */
    private boolean success;
    /**
     * 信息(给用户的提示)
     */
    private String message;
    /**
     * 具体业务数据
     */
    private Object data;

    public R() {
        Error code200 = Error.Code200;
        this.status = code200.getCode();
        this.success = true;
        this.data = code200.getMsg();
    }

    public R(Throwable throwable) {
        if (throwable!=null) {
            if (throwable instanceof GuliException) {
                GuliException exception = (GuliException) throwable;
                this.status = exception.getCode();
                this.message = exception.getMessage();
            } else {
                Error error2001 = Error2001;
                this.status = error2001.getCode();
                this.message = throwable.getMessage();
            }
        }
        this.success = false;
    }

    public R(Object data) {
        this();
        this.data = data;
        this.success = true;
    }

    public R(String key, Object value) {
        Error code200 = Error.Code200;
        JSONObject object = new JSONObject();
        object.put(key, value);
        this.data = object;
        this.success = true;
        this.status = code200.getCode();
    }

    public R(Error error) {
        this.status = error.getCode();
        this.message = error.getMsg();
        this.success = false;
    }
}
